package ynu.edu.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.controller.LogicController;
import ynu.edu.utils.Result;
import ynu.edu.utils.TokenUtils;
import ynu.edu.utils.inna.AuthAccess;
import ynu.edu.dao.IUserDao;
import ynu.edu.dto.AuthDTO;
import ynu.edu.entity.User;
import ynu.edu.service.UserService;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Objects;

@Api(tags = "登陆注册等权限认证控制器")
@RestController
@RequestMapping("/auth")
public class AuthController extends LogicController<UserService, IUserDao, User,Long> {
    @Resource
    private ModelMapper modelMapper;
    public AuthController(@Autowired UserService ls) {
        super(ls);
    }

    @AuthAccess
    @ApiOperation("用户登录")
    @PostMapping("/login")
    @Transactional
    public Result login(@RequestParam("userPhone") String userPhone, @RequestParam("password") String password){
//        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = getService().login(userPhone,  password);
        if (user == null) return Result.error("登录失败");
        //获取token
        String token = TokenUtils.createToken(user.getUserPhone(), user.getPassword());
        user.setToken(token);
        AuthDTO authDTO = modelMapper.map(user, AuthDTO.class);
        return Result.success(authDTO);
    }

    @AuthAccess
    @ApiOperation("用户注册")
    @PostMapping("/register")
    @Transactional
    public Result register(@RequestBody User user){
        User registerUser = getService().register(user);
        if (Objects.isNull(registerUser)){
            return Result.error("注册失败");
        }
        AuthDTO authDTO = modelMapper.map(registerUser, AuthDTO.class);
        return Result.success(authDTO);
    }
}

